//
//  OAuthViewController.swift
//  WeiBo(Swift)
//
//  Created by 周成龙 on 16/9/28.
//  Copyright © 2016年 ZCL. All rights reserved.
//

import UIKit

import SVProgressHUD

class OAuthViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadOAuth()
    }
    
    private func loadOAuth() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=1003610185&redirect_uri=www.baidu.com"
        
        guard let url = NSURL(string: urlString) else {
            return
        }
        
        let request = NSURLRequest(url: url as URL)
        webView.delegate = self
        webView.loadRequest(request as URLRequest)
    }

}

extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.showInfo(withStatus: "加载中...")
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 是否为授权界面
        guard let urlString = request.url?.absoluteString else {
            return false
        }
        
        if !urlString.hasPrefix("http://www.baidu.com") {
            return true
        }
        
        // 取出 code
        let key = "code="
        if urlString.contains(key) {
            let code = request.url?.query?.substring(from: key.endIndex)
            loadAccessToken(codeStr: code)
        }
        return false
    }
    
    private func loadAccessToken(codeStr: String?) {
        guard let code = codeStr  else {
            return
        }
        
        let url = "oauth2/access_token"
        // String: Any
        let dict = ["client_id": "1003610185", "client_secret": "641e826daa333c2f2c332475a4333dc5","grant_type": "authorization_code","code": code,"redirect_uri": "http://www.baidu.com"]
        
        NetworkTools.shareInstence.post(url, parameters: dict, progress: nil, success: { (task: URLSessionDataTask, objc: Any) in
            
            let account = UserAccount(dict: objc as! [String: Any])
            account.loadUserInfo(finished: { (account, error) in
                if error == nil {
                    account?.saveAccount()
                }
            })
            
        }) { (task: URLSessionDataTask?, error: Error?) in
                ZLog(message: error)
        }
    }
}
